package com.wkbb.basic.controller.manage;

import com.github.pagehelper.PageInfo;
import com.wkbb.basic.constant.BasicConstants;
import com.wkbb.basic.model.Employee;
import com.wkbb.basic.service.EmployeeService;
import com.wkbb.basic.service.UserService;
import com.wkbb.basic.vo.EmployeeEditInfoVo;
import com.wkbb.basic.vo.TeacherManageVo;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.ClassInfoDto;
import com.wkbb.common.dto.basic.EmployeeInfoDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.enums.RoleTypeEnum;
import com.wkbb.common.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(description = "员工管理(后台管理)")
@RequestMapping("/basic/{apiVersion}/employee/manage")
@Slf4j
public class EmployeeManageController extends BaseController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private UserService userService;

    @ApiOperation(value = "查询员工分页列表")
    @RequestMapping(value = "/getEmployeePageList", method = RequestMethod.GET)
    public ResultDTO<PageInfo<EmployeeInfoDto>> getEmployeePageList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "姓名", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "手机号", required = false) @RequestParam(name = "mobile", required = false) String mobile,
            @ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        log.info("***********EmployeeController.getEmployeePageList******...apiVersion:{},orgId:{},name:{},mobile:{},pageNo:{},pageSize:{}",apiVersion, orgId, name, mobile, pageNo, pageSize);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        if (null == orgId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {

            if (StringUtils.isEmpty(orgId)) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            HashMap<String, Object> params = new HashMap<>();

            if (null != orgId) {
                params.put("orgId", orgId);
            }

            if (!StringUtil.isNullOrBlank(name)) {
                params.put("name", name);
            }

            if (!StringUtil.isNullOrBlank(mobile)) {
                params.put("mobile", mobile);
            }

            return new ResultDTO<PageInfo<EmployeeInfoDto>>(employeeService.getEmployeePageList(params,pageNo,pageSize));

        } catch (Exception e) {
            log.error("***********EmployeeController.getEmployeePageList******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "查询员工详情")
    @RequestMapping(value = "/getEmployeeById", method = RequestMethod.GET)
    public ResultDTO<EmployeeEditInfoVo> getEmployeeById(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "员工id", defaultValue = "29", required = true) @RequestParam(name = "id", required = true) Long id) {
        log.info("***********EmployeeController.getEmployeeById******...apiVersion:{},Employee:{}", apiVersion, id);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            return new ResultDTO<EmployeeEditInfoVo>(employeeService.getEmployeeInfoById(id));
        } catch (Exception e) {
            log.error("***********EmployeeController.getEmployeeById******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "新增员工")
    @RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
    public ResultDTO<Object> addEmployee(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @RequestBody EmployeeInfoDto employeeInfoDto) {

        log.info("***********EmployeeController.addEmployee******...apiVersion:{},Employee:{}", apiVersion, employeeInfoDto);

        UserDto userDto = getUserByLogin();

        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        if (checkData(employeeInfoDto)) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            ErrorCode result = userService.checkMobileErrorCode(employeeInfoDto.getMobile(), employeeInfoDto.getCardNo(),
                    employeeInfoDto.getJobNo(), (employeeInfoDto.getUserId() == null || employeeInfoDto.getUserId() == 0) ? null : employeeInfoDto.getUserId(),
                    RoleTypeEnum.TEACHER.getValue(), employeeInfoDto.getOrgId(), employeeInfoDto.getAccount(),null);
            if (result != null) {
                return new ResultDTO<>(result);
            }

            //判断当前组织是否有已有该用户
            if (employeeInfoDto.getUserId() != null && employeeInfoDto.getUserId() != 0) {
                Map<String, Object> params = new HashMap<>(2);
                params.put("orgId", employeeInfoDto.getOrgId());
                params.put("userId", employeeInfoDto.getUserId());
                List<EmployeeInfoDto> allEmployeeList = employeeService.getEmployeeList(params);
                if (allEmployeeList != null && !allEmployeeList.isEmpty()) {
                    return new ResultDTO<>(ErrorCode.EMPLOYEE_EXISTS);
                }
            }

            //检查头像checkHeadImgcheckHeadImg
            if (StringUtil.isNullOrBlank(employeeInfoDto.getHeadImgUrl())) {
                employeeInfoDto.setHeadImgUrl("女".equals(employeeInfoDto.getSex()) ? BasicConstants.DEFAULT_HEADIMG_TEACHER_FEMALE :
                        BasicConstants.DEFAULT_HEADIMG_TEACHER_MALE);
            }

            employeeService.insertEmployee(employeeInfoDto,userDto.getName());

            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("***********EmployeeController.addEmployee******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "修改老师")
    @RequestMapping(value = "/updateEmployee", method = RequestMethod.PUT)
    public ResultDTO<EmployeeInfoDto> updateEmployee(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @RequestBody EmployeeInfoDto employeeInfoDto) {

        log.info("***********EmployeeController.updateEmployee******...apiVersion:{},Employee:{}", apiVersion, employeeInfoDto);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        if (employeeInfoDto.getId() == null || employeeInfoDto.getId() == 0
                || employeeInfoDto.getUserId() == null || employeeInfoDto.getUserId() == 0
                || checkData(employeeInfoDto)) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            //后台不会修改手机号
            ErrorCode result = userService.checkMobileErrorCode(null, employeeInfoDto.getCardNo(), employeeInfoDto.getJobNo(),
                    employeeInfoDto.getUserId(), RoleTypeEnum.TEACHER.getValue(), employeeInfoDto.getOrgId(), employeeInfoDto.getAccount(),null);
            if (result != null) {
                return new ResultDTO<>(result);
            }

            Employee employee = new Employee();
            BeanUtils.copyProperties(employeeInfoDto,employee);

            employee.setUpdateBy(userDto.getName());

            employeeService.updateEmployee(employeeInfoDto,userDto.getName(),true,true);

            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("***********EmployeeController.updateEmployee******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "删除老师")
    @RequestMapping(value = "/deleteEmployee", method = RequestMethod.DELETE)
    public ResultDTO deleteEmployee(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "员工id", defaultValue = "29", required = true) @RequestParam(name = "id", required = true) List<Long> ids) {
        log.info("***********EmployeeController.deleteEmployee******...apiVersion:{},ids:{}", apiVersion, Arrays.toString(ids != null ? ids.toArray() : new Object[0]));

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (ids == null || ids.isEmpty()) {
                return new ResultDTO<>();
            }

            for(Long id : ids) {
                Employee employee = new Employee();
                employee.setId(id);
                employeeService.delete(employee);
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********EmployeeController.deleteEmployee******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "查询员工列表")
    @RequestMapping(value = "/getEmployeeList", method = RequestMethod.GET)
    public ResultDTO<List<EmployeeInfoDto>> getEmployeeList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", defaultValue = "1", required = false) @RequestParam(name = "orgId", required = false) Long orgId) {

        log.info("***********TeacherManageController.getTeacherInfoPageList******...apiVersion:{},orgId:{}",apiVersion, orgId);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            HashMap<String, Object> params = new HashMap<>();
            if (null != orgId) {
                params.put("orgId", orgId);
            }

            return new ResultDTO<List<EmployeeInfoDto>>(employeeService.getEmployeeList(params));

        } catch (Exception e) {
            log.error("***********TeacherManageController.getTeacherInfoPageList******", e);
            return new ResultDTO<>(false);
        }
    }

    /**
     * 检查必填项
     *
     * @param employeeInfoDto 员工信息
     * @return 检查是否未通过
     */
    private boolean checkData(EmployeeInfoDto employeeInfoDto) {
        return employeeInfoDto.getOrgId() == null || employeeInfoDto.getOrgId() == 0
                || StringUtil.isNullOrBlank(employeeInfoDto.getOrgName())
                || StringUtil.isNullOrBlank(employeeInfoDto.getMobile())
                || StringUtil.isNullOrBlank(employeeInfoDto.getName());
    }

}
